<script setup>
import { ref, onMounted, watch } from "vue";
import { searchEmpPage, addEmp, getEmpById, updateEmp, deleteByIds } from "@/api/emp.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { queryAll } from "@/api/dept.js";
const page = ref(1);
const pageSize = ref(5);
const total = ref(0);
const empList = ref([]);
const dialogFormVisible = ref(false);
const dialogTitle = ref("");
const selectedIds = ref("[]");
const token = ref('');
const jobs = ref([ //所有职位选项，直接定义好数据
  { value: 1, name: "班主任" },
  { value: 2, name: "讲师" },
  { value: 3, name: "学工主管" },
  { value: 4, name: "教研主管" },
  { value: 5, name: "咨询师" }
]);
const depts = ref([]);
const emp = ref({
  id: '',
  image: '',
  username: '',
  name: '',
  gender: '',
  job: '',
  entryDate: '',
  deptId: '',
  phone: '',
  salary: '',
  exprList: []
})

const searchForm = ref({
  name: '',
  gender: '',
  begin: '',
  end: '',
  daterange: []
});



// 侦听表单的日期值
watch(() => searchForm.value.daterange, (newValue, oldValue) => {
  if (newValue && newValue.length == 2) {
    searchForm.value.begin = newValue[0];
    searchForm.value.end = newValue[1];
  }
})
// 根据表单内容发送请求查询员工列表
async function search() {
  const result = await searchEmpPage(searchForm.value, page.value, pageSize.value);
  if (result.code == 1) {
    console.log(result.data);
    // 展示到表格中
    empList.value = result.data.rows;
    // 数据总数
    total.value = result.data.total;
  } else {
    ElMessage.error("查询用户列表失败");
  }
}
// 清空表单
const clear = () => {
  searchForm.value = {
    name: '',
    gender: '',
    begin: '',
    end: '',
    daterange: []
  };
  search();
}
//每页数量变化时触发
const handleSizeChange = (val) => {
  pageSize.value = val; //将变化后的每页数量 设置给分页条的每页数量数据项
  page.value = 1; //将分页条的页码重新设置为1
  search(); //重新执行分页查询
}

//当前页码变化时触发
const handleCurrentChange = (val) => {
  page.value = val; //将变化后的当前页码 设置给分页条的当前页码
  search(); //重新执行分页查询
}
const handleEdit = async (index, row) => {
  // 查询回显
  const result = await getEmpById(row.id);
  if (result.code == 1) {
    // 修改dialog标题
    dialogTitle.value = "修改员工";
    // 将数据显示到emp中
    emp.value = result.data;
    const exprs = emp.value.exprList;
    exprs.forEach(expr => {
      expr.exprDate = [expr.begin, expr.end];
    })
    // 显示弹窗
    dialogFormVisible.value = true;
  } else {
    ElMessage.error("查询员工失败");
  }
}
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(emp => {
    return emp.id;
  })
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    `将删除员工${row.name},确定继续？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteByIds(row.id);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error("删除失败！");
    }
  });

}

const batchDelete = () => {
  ElMessageBox.confirm(
    `将批量删除选中员工,确定继续？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteByIds(selectedIds.value);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error("删除失败！");
    }
  });
}

const showAddDialog = () => {
  emp.value = {
    id: '',
    image: '',
    username: '',
    name: '',
    gender: '',
    job: '',
    entryDate: '',
    deptId: '',
    phone: '',
    salary: '',
    exprList: []
  };
  dialogTitle.value = "新增员工";
  dialogFormVisible.value = true;
}
// 工作经历操作
const addExpr = () => {
  emp.value.exprList.push({ exprDate: [], company: "", job: "", begin: "", end: "" });
}
const deleteExpr = (index) => {
  emp.value.exprList.splice(index, 1); //删除数组中指定索引的数据，删除数量为1条
}
watch(() => emp.value.exprList, (newV, oldV) => {
  // 一旦工作经历有变化，就将每个工作经历的exprDate(开始与结束日期数组)中的值，分别赋值给此工作经历的begin与end
  newV.forEach(expr => {
    if (expr.exprDate && expr.exprDate.length >= 2) {
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    }
  });
}, { deep: true });

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response, uploadFile) => {
  emp.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
// 保存员工
const save = async () => {
  let result;
  if (emp.value.id !== '') {
    result = await updateEmp(emp.value);
  } else {
    result = await addEmp(emp.value);
  }
  if (result.code == 1) {
    ElMessage.success("保存成功");
    dialogFormVisible.value = false;
    search();
  } else {
    ElMessage.error("保存失败")
  }
}

onMounted(async () => {
  search();
  const result = await queryAll();
  if (result.code == 1) {
    const loginInfo = JSON.parse(localStorage.getItem("loginInfo"))
    token.value = loginInfo.token;
    depts.value = result.data;
  }
})

</script>

<template>
  {{ token }}
  <el-container>
    <el-header style="margin-bottom: 20px;">
      <div> <el-text class="mx-1" type="primary">员工管理</el-text></div>
      <!-- 表单区域 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <!-- 员工姓名 -->
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <!-- 性别选择 -->
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
          <!-- 入职时间选择 -->
        </el-form-item>
        <el-form-item label="入职时间">
          <el-date-picker v-model="searchForm.daterange" type="daterange" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main>
      <!-- 新增按钮 -->
      <div class="btn" style="margin-bottom: 20px;">
        <el-button type="primary" @click="showAddDialog">新增</el-button>
        <el-button type="warning" @click="batchDelete">批量删除</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" prop="name" align="center"></el-table-column>
        <el-table-column prop="gender" label="性别" align="center">
          <template #default="scope">
            <span v-if="scope.row.gender == 1">男</span>
            <span v-else>女</span>
          </template>
        </el-table-column align="center">
        <el-table-column prop="image" label="头像" show-overflow-tooltip>
          <template #default=scoped>
            <img :src="scoped.row.image" alt="" style="height: 50px">
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" align="center" />
        <el-table-column prop="job" label="职位" align="center">
          <template #default="scoped">
            <span v-if="scoped.row.job == 1">班主任</span>
            <span v-else-if="scoped.row.job == 2">讲师</span>
            <span v-else-if="scoped.row.job == 3">学工主管</span>
            <span v-else-if="scoped.row.job == 4">教研主管</span>
            <span v-else>咨询师</span>
          </template>
        </el-table-column align="center">
        <el-table-column prop="entryDate" label="入职日期" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" width="200px" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination v-model:current-page="page" :page-size="pageSize" :page-sizes="[5, 10, 20, 40]"
        layout="sizes, total, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-main>
    <!-- 弹出新增/修改对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="800">
      <el-form label-width="80px" v-model="emp">
        <!-- 第1行：用户名和姓名 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input placeholder="请输入员工用户名，2-20个字" autocomplete="off" v-model="emp.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input placeholder="请输入员工姓名，2-10个字" autocomplete="off" v-model="emp.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第2行：性别和手机号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select placeholder="请选择性别" style="width:100%" v-model="emp.gender">
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input placeholder="请输入员工手机号" autocomplete="off" v-model="emp.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第3行：职位与薪资 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select placeholder="请选择职位" style="width:100%" v-model="emp.job">
                <el-option v-for="job in jobs" :label="job.name" :value="job.value" :key="job.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input placeholder="请输入员工薪资" autocomplete="off" v-model="emp.salary" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第4行：所属部门与入职日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select placeholder="请选择部门" style="width:100%" v-model="emp.deptId">
                <el-option v-for="d in depts" :label="d.name" :value="d.id" :key="d.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker type="date" value-format="YYYY-MM-DD" placeholder="选择入职日期" style="width:100%"
                v-model="emp.entryDate" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第5行：头像 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{'token':token}">
                <!-- 如果image有值就显示头像图片，不然就显示默认的+号图标 -->
                <img v-if="emp.image" :src="emp.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第6行：添加工作经历按钮 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作经历">
              <!-- ↓↓↓↓点击时添加工作经历↓↓↓↓ -->
              <el-button type="success" @click="addExpr">添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第7行：工作经历 -->
        <!-- ↓↓↓↓使用v-for循环emp里的工作经历列表↓↓↓↓ -->
        <el-row :gutter="20" v-for="(expr, index) in emp.exprList" :key="index">
          <el-col :span="9">
            <el-form-item label="时间" label-width="70px">
              <!-- ↓↓↓↓使用v-model将工作的开始与结束日期，绑定给此empr的exprDate↓↓↓↓ -->
              <el-date-picker value-format="YYYY-MM-DD" type="daterange" v-model="expr.exprDate" range-separator="到"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司" label-width="50px">
              <!-- ↓↓↓↓使用v-model将工作公司名称，绑定给此empr的company↓↓↓↓ -->
              <el-input placeholder="请输入公司名称" autocomplete="off" v-model="expr.company" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位" label-width="50px">
              <!-- ↓↓↓↓使用v-model将工作的职位，绑定给此empr的job↓↓↓↓ -->
              <el-input placeholder="请输入职位" autocomplete="off" v-model="expr.job" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="" label-width="0">
              <!-- ↓↓↓↓单击时 从emp的工作经历列表中删除此工作经历↓↓↓↓ -->
              <el-button type="danger" @click="deleteExpr(index)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>

    </el-dialog>
  </el-container>
</template>

<style scoped>
.el-text {
  font-size: 18px;
  font-weight: 500;
  line-height: 50px;
}

.example-pagination-block+.example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>